package account_manage

import (
	"fmt"
	"go_gui/lib"
	"go_gui/logger"
	"io/ioutil"
	"net/http"
	"sort"
)

type cont struct {
	Ver      string
	CrossVer string
}

type ServerConfig struct {
	Owner        string `json:"owner"`        // owner
	Game         string `json:"game"`         // 游戏key
	DbHost       string `json:"dbhost"`       // dbhost
	DbName       string `json:"db"`           // dbname
	ServerName   string `json:"servername"`   // 区服名
	ServerId     string `json:"serverid"`     // 区服id
	SingleServer string `json:"singleserver"` // 是否合服 0合了1没合
	Cont         cont   `json:"_confcont"`    // 版本信息
	OpenTime     string `json:"opentime"`     // 开服时间日期格式
	Ctime        int64  // 开服时间时间戳
}

var CurOwnerList = make([]string, 0)

// GetServerConfigList 获取指定游戏区服配置
func GetServerConfigList(gameKey string, g123Ver string) (serverConfigList []*ServerConfig) {
	if gameKey == "" {
		return
	}

	_url := fmt.Sprintf("http://gametools.legu.cc/?app=api&act=getServerList&game=%s", gameKey)
	if lib.InSlice(gameKey, G123GameKeyList) {
		if g123Ver == "" {
			g123Ver = "stg"
		}
		_url = fmt.Sprintf("https://%s-slb.%s.g123-cpp.com/server-tool/get_server_list_by_gui", gameKey, g123Ver)
	}
	_response, _err := http.Get(_url)
	// url fail
	if _err != nil {
		logger.FyneLog.Warn(fmt.Sprintf("GetServerConfig http.Get error!!\n  gameKey: %s\nerr-->%v", gameKey, _err))
		return
	}
	defer _response.Body.Close()

	_res, _err := ioutil.ReadAll(_response.Body)
	// 数据解析失败
	if _err != nil {
		logger.FyneLog.Warn(fmt.Sprintf("GetServerConfig http.Get error!!\n  gameKey: %s\nerr-->%v", gameKey, _err))
		return
	}

	_err = lib.Loads(_res, &serverConfigList)
	// 转结构失败
	if _err != nil {
		logger.FyneLog.Warn(fmt.Sprintf("GetServerConfig http.Get error!!\n  gameKey: %s\nerr-->%v", gameKey, _err))
		return
	}

	_newList := make([]*ServerConfig, 0)
	//排除跨服、被删除的区服、合区子服
	for _, serverConfig := range serverConfigList {
		if !lib.InSlice(gameKey, G123GameKeyList) {
			if serverConfig.Cont.Ver == "cross" || serverConfig.Owner == "del" || serverConfig.SingleServer == "0" {
				if serverConfig.Owner == "dev" {
					println(serverConfig)
				}
				continue
			}
		} else {
			serverConfig.Game = gameKey
		}
		if !lib.InSlice(serverConfig.Owner, CurOwnerList) {
			CurOwnerList = append(CurOwnerList, serverConfig.Owner)
		}

		serverConfig.Ctime = lib.Time.Date2Now(serverConfig.OpenTime)
		_newList = append(_newList, serverConfig)
	}

	// 按开服时间倒序排序
	sort.Slice(_newList, func(i, j int) bool {
		return _newList[i].Ctime > _newList[j].Ctime
	})
	serverConfigList = _newList

	// 加上正式服
	if g123Ver != "pro" && lib.InSlice(gameKey, G123GameKeyList) {
		_g123ProServerConfigList := GetServerConfigList(gameKey, "pro")
		serverConfigList = append(serverConfigList, _g123ProServerConfigList...)
	}

	return
}
